<template>
  <div id="uploadImage">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :custom-request="handleUpload"
    >
      <img v-if="image?.url" :src="image?.url" alt="img" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或拖拽上传图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { uploadImageUsingPost } from '@/api/imageController.ts'

// 加载参数
const loading = ref<boolean>(false)

// 该组件为受控组件，由父组件（图片创建页面）来管理
interface Props {
  image?: API.ImageVO
  spaceId?: number
  onSuccess?: (newPicture: API.ImageVO) => void
}
const props = defineProps<Props>()

/**
 * 上传图片前的校验
 */
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 允许上传图片类型的数组
  const allowImageType = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
  const isJpgOrPng = allowImageType.includes(file.type)
  if (!isJpgOrPng) {
    message.error('请选择jpeg、jpg、png或者webp图片格式上传!')
  }
  const isLt2M = file.size / 1024 / 1024 <= 2
  if (!isLt2M) {
    message.error('上传图片大小不能超过 2MB!')
  }
  return isJpgOrPng && isLt2M
}

/**
 * 图片上传后的处理
 * @param file 上传的文件
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const params = props.image ? { id: props.image.id } : {}
    params.spaceId = props.spaceId;
    const res = await uploadImageUsingPost(params, {}, file)
    if (res.data.code === 0 && res.data.data) {
      message.success('图片上传成功')
      // 将上传成功的图片信息传递给父组件
      props.onSuccess?.(res.data.data)
    } else {
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    message.error('图片上传失败', error.message)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
#uploadImage :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-height: 152px;
  min-width: 152px;
  margin-bottom: 16px;
}

#uploadImage img {
  max-width: 100%;
  max-height: 480px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}
</style>
